package com.lunhui.user.provider.impl;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.lunhui.user.business.UserService;
import com.lunhui.user.client.UserClient;
import com.lunhui.user.client.model.UserDto;
import com.lunhui.user.dal.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;


/**
 * @author renminghe-kg
 */
@Service
public class UserClientImpl implements UserClient {
    private static final Logger logger = LoggerFactory.getLogger(UserClientImpl.class);

    @Autowired
    @Qualifier("userService")
    private UserService userService;


    @Override
    public Integer saveToDB(String account, String password) {
        try {
            return userService.saveToDB(account, password);
        } catch (Exception e) {
            logger.error("保存账户信息失败: " + e.getMessage());
            throw new RuntimeException("保存账户信息失败: " + e.getMessage() );
        }

    }

    @Override
    public UserDto findByAccount(String account) {
        try {
            UserDto userDto = new UserDto();

            User user = userService.getByAccount(account);

            if (user != null) {
                BeanUtils.copyProperties(user, userDto);
            } else {
                userDto = null;
            }

            return userDto;

        } catch (Exception e) {
            logger.error("获取账户信息失败: " + e.getMessage());
            throw new RuntimeException("获取账户信息失败: " + e.getMessage() );
        }
    }

    @Override
    public UserDto findByAccountAndPassword(String account, String password) throws RuntimeException {
        try {
            UserDto userDto = new UserDto();

            User user = userService.getByAccountAndPassword(account, password);

            if (user != null) {
                BeanUtils.copyProperties(user, userDto);
            } else {
                userDto = null;
            }

            return userDto;

        } catch (Exception e) {
            logger.error("获取账户信息失败: " + e.getMessage());
            throw new RuntimeException("获取账户信息失败: " + e.getMessage() );
        }
    }

    @Override
    public Integer updateUserInfo(UserDto userDto) throws RuntimeException {
        try {
            User user = new User();
            BeanUtils.copyProperties(userDto, user);

            return userService.updateUserInfo(user);

        } catch (Exception e) {
            logger.error("更新账户信息失败: " + e.getMessage());
            throw new RuntimeException("更新账户信息失败: " + e.getMessage() );
        }
    }
}